package cn.jinjimi.app.main.activity;

import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.TextView;

import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.FileUtils;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceWhenTrue;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.app.controller.event.LogoutEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeNewVersionEvent;
import cn.jinjimi.domain.data.Cache;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.store.entity.NoticeEntity;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.util.AppUtils;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

/**
 * Created by m1 on 15/1/22.
 */
public class SettingActivity extends ToolBarCommonActivity {

    public static final String TAG = SettingActivity.class.getSimpleName();
    private TextView mLoginStateTv = null;
    private ImageView ivUpdateIcon;

    private TextView tvCacheSize;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_settings);
        setTitle(R.string.me_settings_title);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mLoginStateTv = (TextView) findViewById(R.id.rl_logout_textview);
        ivUpdateIcon = (ImageView) findViewById(R.id.iv_me_setting_new);

        tvCacheSize = (TextView) findViewById(R.id.tv_cache_size);
        initLoginState();
    }

    private void initData() {
        setCacheSize();
        NoticeManager.getNoticesByCode(NoticeEntity.TypeNewVersion);
    }

    private void initLoginState() {
        if (AccountManager.getInstance().isLogin()) {
            mLoginStateTv.setText(R.string.set_logout);
        } else {
            mLoginStateTv.setText(R.string.login_now);
        }
    }

    protected void initListener() {
        findViewById(R.id.rl_update).setOnClickListener(this);
        findViewById(R.id.rl_aboutus).setOnClickListener(this);
        findViewById(R.id.rl_product).setOnClickListener(this);

        findViewById(R.id.rl_clear_cache).setOnClickListener(this);
        findViewById(R.id.rl_logout).setOnClickListener(this);
        findViewById(R.id.rl_feedback).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_update:
                //ToastUtil.showLoading(this, getResources().getString(R.string.set_checking_update));
                //checkUpdate();
                break;
            case R.id.rl_feedback:
                break;
            case R.id.rl_aboutus:
                //AboutUsActivity.launchMe(this);
                break;
            case R.id.rl_product:
                break;
            case R.id.rl_logout:
                //logoutOrLogin(AccountManager.getInstance().isLogin());
                break;
            case R.id.rl_clear_cache:
                //showClearCacheDialog();
                break;
            default:break;
        }
    }

    @EventTrace(EventID.APP_OWNER_SET_LOGOUT)
    private void logoutOrLogin(@EventTraceWhenTrue boolean isLogin) {
        if (isLogin) {
            logout();
        } else {
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    /* 获取缓存大小 */
    private void setCacheSize() {
        long size = FileUtils.getFolderSize(new File(Cache.getAppDataPath()));
        if (size > 0) {
            tvCacheSize.setText(FileUtils.formatFileSize(size));
            tvCacheSize.setVisibility(View.VISIBLE);
        } else {
            tvCacheSize.setVisibility(View.GONE);
        }
    }

    //清除缓存
    @EventTrace(EventID.APP_OWNER_SET_CLEARCACHE)
    private void showClearCacheDialog() {
        CommAlertDialog clearCacheDialog = getAlertDialog();
        clearCacheDialog.setTitle(getString(R.string.set_clear_cache_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        clearCache();
                    }
                });
        clearCacheDialog.showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    private void clearCache() {
        LoadingDialog.show(SettingActivity.this, getString(R.string.set_clearing_cache));

        TaskExecutor.executeTask(new Runnable() {
            @Override
            public void run() {

                FileUtils.deleteAllFile(Cache.getAppDataPath());

                AndroidUtils.scanFiles(SettingActivity.this, Cache.getAppDataPath());

                TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
                    @Override
                    public void run() {
                        LoadingDialog.dispose();
                        setCacheSize();
                    }
                });
            }
        });
    }

    //退出登录
    private void logout() {
        getAlertDialog().setTitle(getString(R.string.set_logout_msg))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        LoadingDialog.show(SettingActivity.this, getString(R.string.logouting));
                        UserController.logout();

                    }
                });
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeNewVersionEvent(NoticeNewVersionEvent event) {
        ivUpdateIcon.setVisibility(event.count > 0 ? View.VISIBLE : View.INVISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent event) {
        initLoginState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogoutEvent(LogoutEvent event) {
        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                ToastUtil.showLoading(SettingActivity.this, getString(R.string.set_clear_info));

                //remove all session cookies
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    CookieManager.getInstance().removeSessionCookies(new ValueCallback<Boolean>() {
                        @Override
                        public void onReceiveValue(Boolean value) {
                            LogUtil.d(TAG, "remove all session cookies");
                        }
                    });
                }

                AccountManager.getInstance().logout();

                AppUtils.onLoginStateChange(this);

                EventBus.getDefault().post(new LoginSuccessEvent());
                TaskExecutor.scheduleTaskOnUiThread(500, new Runnable() {
                    @Override
                    public void run() {
                        hideLoadingIndicator();
                        finish();
                    }
                });

                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(SettingActivity.this, R.string.logout_fail);
                break;
        }
    }

    @EventTrace(EventID.APP_OWNER_SET_CHECKUPDATE)
    private void checkUpdate() {

    }
}
